<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="motan,源码,Protocol,点对点通讯" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="protocol可以说是motan最重要的部分之一。 暴露一个服务引用一个服务都是在这块实现的。 1234567891011121314151617181920212223242526272829303132@Spi(scope = Scope.SINGLETON)public interface Protocol &amp;#123;    /**     * 暴露服务     *      * @pa">
<meta name="keywords" content="motan,源码,Protocol,点对点通讯">
<meta property="og:type" content="article">
<meta property="og:title" content="Motan源码解读-Protocol">
<meta property="og:url" content="http://www.zhizus.com/2016-09-21-motan-protocol.html">
<meta property="og:site_name" content="郑大侠的博客">
<meta property="og:description" content="protocol可以说是motan最重要的部分之一。 暴露一个服务引用一个服务都是在这块实现的。 1234567891011121314151617181920212223242526272829303132@Spi(scope = Scope.SINGLETON)public interface Protocol &amp;#123;    /**     * 暴露服务     *      * @pa">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://www.zhizus.com/images/motan/Protocol.png">
<meta property="og:updated_time" content="2018-06-04T02:56:46.724Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Motan源码解读-Protocol">
<meta name="twitter:description" content="protocol可以说是motan最重要的部分之一。 暴露一个服务引用一个服务都是在这块实现的。 1234567891011121314151617181920212223242526272829303132@Spi(scope = Scope.SINGLETON)public interface Protocol &amp;#123;    /**     * 暴露服务     *      * @pa">
<meta name="twitter:image" content="http://www.zhizus.com/images/motan/Protocol.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: "",
      labels: ""
    }
  };
</script>



  <link rel="canonical" href="http://www.zhizus.com/2016-09-21-motan-protocol.html"/>





  <title> Motan源码解读-Protocol | 郑大侠的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f75c9cec9ecead0dfce9a108b9688072";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑大侠的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-crossed">
          <a href="http://zhizus.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            穿越
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.zhizus.com/2016-09-21-motan-protocol.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="DempeZheng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑大侠的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Motan源码解读-Protocol
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2016-09-21-motan-protocol.html" class="leancloud_visitors" data-flag-title="Motan源码解读-Protocol">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>protocol可以说是motan最重要的部分之一。
暴露一个服务引用一个服务都是在这块实现的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Spi</span>(scope = Scope.SINGLETON)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Protocol</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 暴露服务</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> provider</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> url</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">export</span><span class="params">(Provider&lt;T&gt; provider, URL url)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 引用服务</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> clz</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> url</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> serviceUrl</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    &lt;T&gt; <span class="function">Referer&lt;T&gt; <span class="title">refer</span><span class="params">(Class&lt;T&gt; clz, URL url, URL serviceUrl)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * &lt;pre&gt;</span></span><br><span class="line"><span class="comment">	 * 		1） exporter destroy</span></span><br><span class="line"><span class="comment">	 * 		2） referer destroy</span></span><br><span class="line"><span class="comment">	 * &lt;/pre&gt;</span></span><br><span class="line"><span class="comment">     * </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>Provider</li>
</ul>
<blockquote>
<p>服务提供方，通常可以认为是server端</p>
</blockquote>
<ul>
<li>Exporter</li>
</ul>
<blockquote>
<p>服务提供Provider暴露出去就变成Exporter，服务使用方（客户端）可以调用暴露出去的Provider</p>
</blockquote>
<ul>
<li>Referer</li>
</ul>
<blockquote>
<p>引用服务，引用的服务会通过配置去调用服务端暴露的服务</p>
</blockquote>
<p>现在我们应该会有一定的认识，对于protocol。不管是暴露服务还是引用服务都是通过protocol来实现的。可以说他是学习motan的一个入口。</p>
<p>我们看到这个接口上面也有@SPI注解，就是说protocol可以基于spi机制扩展，<code>也就说你可以对motan进行为所欲为的扩展</code>。</p>
<h2 id="protocol的实现"><a href="#protocol的实现" class="headerlink" title="protocol的实现"></a>protocol的实现</h2><p><img src="/images/motan/Protocol.png" alt=""></p>
<p>这里面再次用到了<code>模板方法设计模式</code>。</p>
<p>下面看我们看AbstractProtocol抽象类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractProtocol</span> <span class="keyword">implements</span> <span class="title">Protocol</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 存放本地export的服务，用于injvm的时候查找本地服务</span></span><br><span class="line">    <span class="keyword">protected</span> ConcurrentHashMap&lt;String, Exporter&lt;?&gt;&gt; exporterMap = <span class="keyword">new</span> ConcurrentHashMap&lt;String, Exporter&lt;?&gt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> Map&lt;String, Exporter&lt;?&gt;&gt; getExporterMap() &#123;</span><br><span class="line">        <span class="keyword">return</span> Collections.unmodifiableMap(exporterMap);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">export</span><span class="params">(Provider&lt;T&gt; provider, URL url)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (url == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> MotanFrameworkException(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" export Error: url is null"</span>,</span><br><span class="line">                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (provider == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> MotanFrameworkException(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" export Error: provider is null, url="</span> + url,</span><br><span class="line">                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        String protocolKey = MotanFrameworkUtil.getProtocolKey(url);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">synchronized</span> (exporterMap) &#123;</span><br><span class="line">            Exporter&lt;T&gt; exporter = (Exporter&lt;T&gt;) exporterMap.get(protocolKey);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (exporter != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> MotanFrameworkException(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" export Error: service already exist, url="</span> + url,</span><br><span class="line">                        MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            exporter = createExporter(provider, url);</span><br><span class="line">            exporter.init();</span><br><span class="line"></span><br><span class="line">            exporterMap.put(protocolKey, exporter);</span><br><span class="line"></span><br><span class="line">            LoggerUtil.info(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" export Success: url="</span> + url);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> exporter;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">Referer&lt;T&gt; <span class="title">refer</span><span class="params">(Class&lt;T&gt; clz, URL url)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> refer(clz, url, url);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> &lt;T&gt; <span class="function">Referer&lt;T&gt; <span class="title">refer</span><span class="params">(Class&lt;T&gt; clz, URL url, URL serviceUrl)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (url == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> MotanFrameworkException(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" refer Error: url is null"</span>,</span><br><span class="line">                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (clz == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> MotanFrameworkException(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" refer Error: class is null, url="</span> + url,</span><br><span class="line">                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Referer&lt;T&gt; referer = createReferer(clz, url, serviceUrl);</span><br><span class="line">        referer.init();</span><br><span class="line"></span><br><span class="line">        LoggerUtil.info(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" refer Success: url="</span> + url);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> referer;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 用于子类扩展，通过扩展这个方法，可以使服务端暴露出自定义的服务。</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">abstract</span> &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">createExporter</span><span class="params">(Provider&lt;T&gt; provider, URL url)</span></span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用于子类扩展，通过扩展这个方法，可以使客户端有自定义的服务引用。</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">abstract</span> &lt;T&gt; <span class="function">Referer&lt;T&gt; <span class="title">createReferer</span><span class="params">(Class&lt;T&gt; clz, URL url, URL serviceUrl)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (String key : exporterMap.keySet()) &#123;</span><br><span class="line">            Node node = exporterMap.remove(key);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (node != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    node.destroy();</span><br><span class="line"></span><br><span class="line">                    LoggerUtil.info(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" destroy node Success: "</span> + node);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">                    LoggerUtil.error(<span class="keyword">this</span>.getClass().getSimpleName() + <span class="string">" destroy Error"</span>, t);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果我们需要实现自己的Export或者Referer，我们继承AbstractProtocol这个方法覆盖里面的两个抽象方法就好了。</p>
<p>比如说，我们希望motan支持protobuf或者thrift，那么我们继承AbstractProtocol这个抽象类，分别实现createExporter，createReferer方法。</p>
<p>那么这两个方法怎么实现呢？</p>
<p>我们来看motan给出的一个默认实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpiMeta</span>(name = <span class="string">"motan"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultRpcProtocol</span> <span class="keyword">extends</span> <span class="title">AbstractProtocol</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 多个service可能在相同端口进行服务暴露，因此来自同个端口的请求需要进行路由以找到相应的服务，同时不在该端口暴露的服务不应该被找到</span></span><br><span class="line">    <span class="comment">// ProviderMessageRouter负责了服务端消息的路由调用，同时也负责了心跳的逻辑</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, ProviderMessageRouter&gt; ipPort2RequestRouter = <span class="keyword">new</span> HashMap&lt;String, ProviderMessageRouter&gt;();</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">createExporter</span><span class="params">(Provider&lt;T&gt; provider, URL url)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultRpcExporter&lt;T&gt;(provider, url);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> &lt;T&gt; <span class="function">Referer&lt;T&gt; <span class="title">createReferer</span><span class="params">(Class&lt;T&gt; clz, URL url, URL serviceUrl)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultRpcReferer&lt;T&gt;(clz, url, serviceUrl);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * rpc provider</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@author</span> maijunsheng</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">DefaultRpcExporter</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractExporter</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> Server server;</span><br><span class="line">        <span class="keyword">private</span> EndpointFactory endpointFactory;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">DefaultRpcExporter</span><span class="params">(Provider&lt;T&gt; provider, URL url)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">super</span>(provider, url);</span><br><span class="line">            ProviderMessageRouter requestRouter = initRequestRouter(url);</span><br><span class="line">            endpointFactory =</span><br><span class="line">                    ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension(</span><br><span class="line">                            url.getParameter(URLParamType.endpointFactory.getName(), URLParamType.endpointFactory.getValue()));</span><br><span class="line">            <span class="comment">//创建server，目前motan仅实现了NettyServer（ExtensionLoader出现代表是可以扩展的，可以扩展自己的server）</span></span><br><span class="line">            server = endpointFactory.createServer(url, requestRouter);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">unexport</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            String protocolKey = MotanFrameworkUtil.getProtocolKey(url);</span><br><span class="line">            String ipPort = url.getServerPortStr();</span><br><span class="line">            Exporter&lt;T&gt; exporter = (Exporter&lt;T&gt;) exporterMap.remove(protocolKey);</span><br><span class="line">            <span class="keyword">if</span> (exporter != <span class="keyword">null</span>) &#123;</span><br><span class="line">                exporter.destroy();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">synchronized</span> (ipPort2RequestRouter) &#123;</span><br><span class="line">                ProviderMessageRouter requestRouter = ipPort2RequestRouter.get(ipPort);</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (requestRouter != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    requestRouter.removeProvider(provider);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            LoggerUtil.info(<span class="string">"DefaultRpcExporter unexport Success: url=&#123;&#125;"</span>, url);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">doInit</span><span class="params">()</span> </span>&#123;</span><br><span class="line">           <span class="comment">//打开服务，</span></span><br><span class="line">            <span class="keyword">boolean</span> result = server.open();</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isAvailable</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> server.isAvailable();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            endpointFactory.safeReleaseResource(server, url);</span><br><span class="line">            LoggerUtil.info(<span class="string">"DefaultRpcExporter destory Success: url=&#123;&#125;"</span>, url);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">private</span> ProviderMessageRouter <span class="title">initRequestRouter</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">            ProviderMessageRouter requestRouter = <span class="keyword">null</span>;</span><br><span class="line">            String ipPort = url.getServerPortStr();</span><br><span class="line">            <span class="keyword">synchronized</span> (ipPort2RequestRouter) &#123;</span><br><span class="line">                requestRouter = ipPort2RequestRouter.get(ipPort);</span><br><span class="line">                <span class="keyword">if</span> (requestRouter == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    requestRouter = <span class="keyword">new</span> ProviderProtectedMessageRouter(provider);</span><br><span class="line">                    ipPort2RequestRouter.put(ipPort, requestRouter);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    requestRouter.addProvider(provider);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> requestRouter;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * rpc referer</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@author</span> maijunsheng</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">DefaultRpcReferer</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractReferer</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> Client client;</span><br><span class="line">        <span class="keyword">private</span> EndpointFactory endpointFactory;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">DefaultRpcReferer</span><span class="params">(Class&lt;T&gt; clz, URL url, URL serviceUrl)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">super</span>(clz, url, serviceUrl);</span><br><span class="line"></span><br><span class="line">            endpointFactory =</span><br><span class="line">                    ExtensionLoader.getExtensionLoader(EndpointFactory.class).getExtension(</span><br><span class="line">                            url.getParameter(URLParamType.endpointFactory.getName(), URLParamType.endpointFactory.getValue()));</span><br><span class="line">            <span class="comment">// 创建client</span></span><br><span class="line">            client = endpointFactory.createClient(url);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 用这个协议的服务，每次调用必经过这个方法</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> Response <span class="title">doCall</span><span class="params">(Request request)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// 为了能够实现跨group请求，需要使用server端的group。</span></span><br><span class="line">                request.setAttachment(URLParamType.group.getName(), serviceUrl.getGroup());</span><br><span class="line">                <span class="keyword">return</span> client.request(request);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (TransportException exception) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> MotanServiceException(<span class="string">"DefaultRpcReferer call Error: url="</span> + url.getUri(), exception);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">decrActiveCount</span><span class="params">(Request request, Response response)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (response == <span class="keyword">null</span> || !(response <span class="keyword">instanceof</span> Future)) &#123;</span><br><span class="line">                activeRefererCount.decrementAndGet();</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            Future future = (Future) response;</span><br><span class="line">            future.addListener(<span class="keyword">new</span> FutureListener() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">operationComplete</span><span class="params">(Future future)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                    activeRefererCount.decrementAndGet();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">doInit</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="comment">// 打开client</span></span><br><span class="line">            <span class="keyword">boolean</span> result = client.open();</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isAvailable</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> client.isAvailable();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            endpointFactory.safeReleaseResource(client, url);</span><br><span class="line">            LoggerUtil.info(<span class="string">"DefaultRpcReferer destory client: url=&#123;&#125;"</span> + url);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ProviderMessageRouter：这个类也比较核心，call方法处理了Server消息路由调用的逻辑，handle方法理了心跳的逻辑</p>
<hr>
<p>后记：看到这里，觉得motan真心不错，虽然功能算不上丰富，但是处处留了扩展的入口。所以还在纠结要不要用motan的可以不用纠结了，即便你需要的功能motan没有覆盖到，
但是你多半也可以扩展去改造它。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>大侠劫富济贫啦！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/dempe/20180527112524.jpg" alt="DempeZheng WeChat Pay"/>
        </div>
      
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016-09-21-motan-hastratege.html" rel="next" title="Motan源码解读-容错策略">
                <i class="fa fa-chevron-left"></i> Motan源码解读-容错策略
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016-09-22-motan-serialize.html" rel="prev" title="Motan源码解读-serialize">
                Motan源码解读-serialize <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466"
               alt="DempeZheng" />
          <p class="site-author-name" itemprop="name">DempeZheng</p>
           
              <p class="site-description motion-element" itemprop="description">請更固執，將自己謀生與擅長的事情做到最好</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">68</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/dempeZheng" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://music.163.com/#/user/home?id=6758793" target="_blank" title="网易云音乐">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  网易云音乐
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dempe" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wolfbe.com/" title="朗度云" target="_blank">朗度云</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#protocol的实现"><span class="nav-number">1.</span> <span class="nav-text">protocol的实现</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">DempeZheng</span>
</div>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("dhzMp0HdJLWMCrt04bwybWzH-gzGzoHsz", "gH6FmxJiUaVLLRXQDWpkkIVv");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

</body>
</html>
